import { createLayer } from '../libs/layers'

export default {
  name: 'MapOperateLayers',
  inject: ['myMap'],
   /**
   * 属性参数, 继承
   * @member props
   * @property {array} [layers] 图层列表
   * @property {string} [layers.title] 图层标题
   * @property {string} [layers.preview] 图层选项预览图
   * @property {string} [layers.type] 图层ID 或 获取图层的方法
   * @property {string} [layers.type] 图层ID 或 获取图层的方法
   */
  props: {
    layers: {
      type: Array,
      default: () => []
    }
  },
  data () {
    return {
      showLayers: []
    }
  },
  created () {
    this.showLayers = this.pDataCreateLayers()
  },
  methods: {
    pDataCreateLayers () {
      return this.layers.map(item => {
        return {
          ...item,
          layer: createLayer(item)
        }
      })
    },
    addLayers (layer) {
      const { map } = this.myMap
      if (layer.layer) {
        map.addLayer(layer.layer)
      } else {
        const addlayer = {
          ...layer,
          layer: createLayer(layer)
        }
        map.addLayer(addlayer.layer)
        this.showLayers.push(addlayer)
        this.$emit('input', [...this.layers, addlayer])
      }
    },
    removeLayer (layer) {
      const { map } = this.myMap
      if (layer.layer) {
        map.removeLayer(layer.layer)
      } else {
        this.showLayers.forEach((item, index) => {
          if (item.title === layer.title) {
            map.remove(item.layer)
          }
        })
        const result = this.layers.filtter(item => {
          return item.title !== layer.title
        })
        this.$emit('input', [...result])
      }
    }
  }
}
